package com.tanklab.signature.common.util;

import com.tanklab.signature.eth.ChainConnection;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

@Component
public class ChainUtils {

    @Value("${app.environment:dev}")
    private  String environment;

    @Value("${app.chain.mock-in-dev:true}")
    private  boolean mockChainInDev;

    @Value("${app.chain.mock-tx-prefix:DEV-TX-}")
    private  String mockTxPrefix;

    /**
     * 根据环境执行上链操作或返回模拟交易ID
     *
     * @param hash 要上链的哈希值
     * @param type 交易类型标识，用于生成模拟ID
     * @return 交易ID
     */
    public  String sendHashToChain(String hash, String type) {
        if (shouldPerformRealChainOperation()) {
            try {
                String txId = ChainConnection.sendHashToChain(hash);
                System.out.println(type + " 上链成功，交易ID: " + txId);
                return txId;
            } catch (ChainConnection.BlockchainException e) {
                System.err.println(type + " 上链失败: " + e.getMessage());
                e.printStackTrace();
                String mockId = generateMockTxId(type);
                System.out.println("使用模拟交易ID: " + mockId);
                return mockId;
            }
        } else {
            // 开发环境使用模拟交易ID
            String mockId = generateMockTxId(type);
            System.out.println("开发环境使用模拟交易ID: " + mockId);
            return mockId;
        }
    }

    /**
     * 判断是否应该执行真实的上链操作
     */
    private  boolean shouldPerformRealChainOperation() {
//        System.out.println("当前环境: " + environment);
//        System.out.println("是否在开发环境中使用模拟链: " + mockChainInDev);
        return "prod".equalsIgnoreCase(environment) || !mockChainInDev;
    }

    /**
     * 生成模拟的交易ID
     */
    private  String generateMockTxId(String type) {
        return mockTxPrefix + type + "-" + System.currentTimeMillis();
    }
}